//app.js
var moment = require('./utils/moment.min.js');
const md5 = require('/utils/md5.js');
App({
  onLaunch: function() {
    var that = this;
    let tt = new Date().getTime();
    let token = that.globalData.token;
    let sign = md5.md5(token + '.' + tt).toUpperCase();
    that.globalData.sign = sign;
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId      
        if (res.code) {
          var code = res.code;
          wx.request({
            url: that.globalData.baseUrl + 'doctor/wx/getOpenId',
            data: {
              'code': code,
              'type': 2
            },
            header: {
              'sign': sign,
              'token': that.globalData.token,
              'tt':tt,
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            },
            method: 'POST',
            success: function(t) {
              that.globalData.token = t.header.token;
              wx.setStorageSync("openid", t.data.data[0].openId);
              wx.setStorageSync("token", that.globalData.token);
              that.loadings();
            }
          })
        }
      }
    })
  },
  loadings: function () {
    const that = this;
    var userInfo = wx.getStorageSync("userInfo");
    if (userInfo == '') {
      wx.redirectTo({
        url: '/pages/shouquan/shouquan',
      })
      return;
    }
    var auditState = wx.getStorageSync('auditState');

    let tt = new Date().getTime();
    let token = that.globalData.token;
    let sign = md5.md5(token + '.' + tt).toUpperCase();
    that.globalData.sign = sign;

    wx.request({
      url: that.globalData.baseUrl + 'doctor/member/isLogin',
      data: {},
      header: {
        'sign': that.globalData.sign,
        'token': that.globalData.token,
        'tt':tt,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
      },
      method: 'POST',
      success(res) {
        wx.setStorageSync('isLogin', res.data.data[0].isLogin)
        if (res.data.data[0].isLogin == 1) {
          if (auditState == 2) {
            //审核通过
            wx.redirectTo({
              url: '/pages/doctor-index/doctor-index',
            });
          } else if (auditState == 3) {
            //未通过
            wx.reLaunch({
              url: '/pages/doctor-authentication-1/doctor-authentication-1',
            });
          } else {
            //待审核          
            wx.reLaunch({
              url: '/pages/doctor-login/doctor-login',
            });
          }
        } else {
          if (auditState == 2) {
            //审核通过
            wx.reLaunch({
              url: '/pages/doctor-login/doctor-login',
            });
          } else if (auditState == 3) {
            //未通过
            wx.reLaunch({
              url: '/pages/doctor-authentication-1/doctor-authentication-1',
            });
          } else {
            //待审核   
            wx.reLaunch({
              url: '/pages/doctor-login/doctor-login',
            });
          }
        }
      }
    })
  },
  //多张图片上传
  uploadimg: function(data) {
    var that = this,
      i = data.i ? data.i : 0, //当前上传的哪张图片
      success = data.success ? data.success : 0, //上传成功的个数
      fail = data.fail ? data.fail : 0; //上传失败的个数
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      formData: null, //这里是上传图片时一起上传的数据
      success: (resp) => {
        success++; //图片上传成功，图片上传成功的变量+1
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
       
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用          
         
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data); locationaddress
        }
      }
    })
  },

  globalData: {
    token: wx.getStorageSync('token')||'',
    sign: "testsign",
    apppid: "wxdd282833d5b93e24",
    // baseUrl: "https://tyc-bj.cn/yc/api/",         // 生产
    // staticimgUrl: "https://tyc-bj.cn/yc/api/attach/images/",
    // imgUrl: "https://tyc-bj.cn/yc/api/attach/", // 请求接口图片、视频路径
    baseUrl: "https://text.tyc-bj.cn/yc/api/",  // 测试
    staticimgUrl: "https://text.tyc-bj.cn/yc/api/attach/images/",
    imgUrl: "https://text.tyc-bj.cn/yc/api/attach/", // 请求接口图片、视频路径
    consigneeid: '',
    consigneename: '',
    consigneephone: '',
    consigneeaddress: ''
  },
  /**
   * loading加载
   */
  showLoading: function() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
  },
  /**
   * 提示消息
   */
  showModal: function(content) {
    // 显示模态弹窗
    wx.showModal({
      title: '提示消息',
      content: content,
      showCancel: false
    });
  },
  showToast: function (content) {
    wx.showToast({
      title: content,
      icon: 'success',
      duration: 1500
    })
  },
 
  /**
   * 网络数据请求功能
   */
  request: function(param) {
    const that = this;
    const path = param.url ? param.url : '';
    let url = this.globalData.baseUrl + param.url;
    let data = param.data || {};

    let tt = new Date().getTime();
    let token = that.globalData.token;
    let sign = md5.md5(token + '.' + tt).toUpperCase();
    wx.request({
      url: url,
      data: data,
      header: {
        'sign': sign,
        'token': that.globalData.token,
        'tt':tt,
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
      },
      method: param.method || 'POST',
      success: function(res) {
        let data= res.data;
        if (data.status_code == 200) {
          typeof param.success(data);
        } else if (data.status_code == 200002 || data.status_code == 500001) {
          //跳转到登入界面
          wx.reLaunch({
            url: '/pages/doctor-login/doctor-login'
          });
        } else {
          that.showModal(data.message);
          if (param.fail){
            typeof param.fail(res.data);
          }
        }
      },
      fail: function(err) {
        // 隐藏loading
        wx.hideLoading();
        // 提示失败信息
        wx.showToast({
          title: '请检查网络链接',
          icon: 'none'
        });
      }
    })
  },
  /**
   * 图片上传
   */
  uploadFile: function (param) {
    const that = this;
    let url = this.globalData.baseUrl + param.url;
    let filePath = param.filePath;
    let data = param.data || {};

    let tt = new Date().getTime();
    let token = that.globalData.token;
    let sign = md5.md5(token + '.' + tt).toUpperCase();

    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: "file",
      header: {
        'sign': sign,
        'token': that.globalData.token,
        'tt':tt,
        'Content-Type': 'multipart/form-data'
      },
      success: function (res) {
        typeof param.success(res);
      },
      fail: function (e) {}
    })
  },
  /**
   * 字段验证
   */
  validate: function(value, type, pattern) {
    // 非空
    if (type === 'required') {
      return !!value;
    }
    // 手机号
    if (type === 'phone') {
      return /^1\d{10}$/.test(value);
    }
    // 数字加字母
    if (type === 'alphanumeric') {
      return /^[A-Za-z0-9]+$/.test(value);
    }
    // 数字
    if (type === 'number') {
      return /^\d+(\.\d+)?$/.test(value);
    }
    // 价格
    if (type === "price"){
      return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value);
    }
  
    // 身份证号
    if (type === 'idNumber') {
      return /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value);
    }
  },
  /**
   * 时间戳转日期格式（YYYY-MM-dd HH:mm:ss）
   */
  timeData(inputTime) {
    return moment(inputTime).format('YYYY-MM-DD');
  }
})